package com.doge.walknovel.widgets.imagecropper

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View

class OverlayView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
    private var mWidth = 0
    private var mHeight = 0
    var overlayWidth = 0
        private set
    var overlayHeight = 0
        private set
    private var mCenterX = 0
    private var mCenterY = 0
    private var mBmpOverlay: Bitmap? = null
    private var isCircleOverlay = false
    public override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mWidth = w
        mHeight = h
        mCenterX = mWidth / 2
        mCenterY = mHeight / 2
    }

    fun reset(outputWidth: Int, outputHeight: Int, isCircleOverlay: Boolean) {
        this.isCircleOverlay = isCircleOverlay
        overlayWidth = (Math.min(mWidth, mHeight) * if (isCircleOverlay) 0.70f else 0.95f).toInt()
        overlayHeight = (1f * overlayWidth * outputHeight / outputWidth).toInt()
        mBmpOverlay = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888)
        val maskCanvas = Canvas(mBmpOverlay!!)
        val maskPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        maskCanvas.drawColor(0x66000000)
        maskPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT)
        if (isCircleOverlay()) {
            maskCanvas.drawCircle(mCenterX.toFloat(), mCenterY.toFloat(), overlayWidth / 2.toFloat(), maskPaint)
        } else {
            maskCanvas.drawRect(mCenterX - overlayWidth / 2.toFloat(), mCenterY - overlayHeight / 2.toFloat(), mCenterX + overlayWidth / 2.toFloat(), mCenterY + overlayHeight / 2.toFloat(), maskPaint)
        }
        maskPaint.xfermode = null
        maskPaint.color = Color.WHITE
        maskPaint.style = Paint.Style.STROKE
        maskPaint.strokeWidth = 4f
        if (isCircleOverlay()) {
            maskCanvas.drawCircle(mCenterX.toFloat(), mCenterY.toFloat(), overlayWidth / 2.toFloat(), maskPaint)
        } else {
            maskCanvas.drawRect(mCenterX - overlayWidth / 2.toFloat(), mCenterY - overlayHeight / 2.toFloat(), mCenterX + overlayWidth / 2.toFloat(), mCenterY + overlayHeight / 2.toFloat(), maskPaint)
        }
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        mBmpOverlay?.let { canvas.drawBitmap(it, 0f, 0f, null) }
    }

    fun isCircleOverlay(): Boolean {
        return isCircleOverlay && overlayWidth == overlayHeight
    }

    init {
        setLayerType(LAYER_TYPE_SOFTWARE, null)
    }
}
